import Vue from 'vue'
import Vuex from 'vuex'
import Storage from './storage'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 用户信息
    user: null
  },
  getters: {
    isAdmin: state => {
      let isAdmin = state.user.role === 'admin'
      console.log('this.$store.getters.isAdmin:', isAdmin)
      return isAdmin
    },
    isTeacher: state => {
      let isTeacher = state.user.role === 'teacher'
      console.log('this.$store.getters.isTeacher', isTeacher)
      return isTeacher
    },
    isStudent: state => {
      let isStudent = state.user.role === 'student'
      console.log('this.$store.getters.isStudent', isStudent)
      return isStudent
    },
    getUser: (state) => {
      if (state.user == null) {
        state.user = Storage.get('user')
      }
      return state.user
    }
  },
  mutations: {
    updateUser (state, val) {
      console.log('this.$store.commit.updateUser', val)
      state.user = val
      Storage.set('user', val)
    },
    userSignOut (state) {
      console.log('this.$store.commit.userSignOut')
      // 清空 vuex
      state.user = null
      // 清空 localStorage
      Storage.remove('user')
    }
  }
})
